﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SharingCenter.Web.Classes.Contact
{
    using SharingCenter.Web.Classes;
    using SharingCenter.Web.Classes.enums;
    using System.Xml.Linq;
    using SharingCenter.Web.Classes.Messages;
    public partial class ContactOperations
    {
        public static bool AreUsersContacts(Guid userId1, Guid userId2)
        {
            using (scDataContext cxt = new scDataContext())
            {
                if (userId1 != userId2)
                {
                    //scDataContext.Instance.Refresh(System.Data.Linq.RefreshMode.KeepChanges, scDataContext.Instance.Sc_Contacts);
                    var q = from t in cxt.Sc_Contacts
                            where t.UserIdA == userId1 && t.USerIdB == userId2 ||
                            t.UserIdA == userId2 && t.USerIdB == userId1
                            select t;
                    return q.Count() > 0;
                }
                else
                {
                    return true;
                }
            }
        }

        public static Sc_SharedRequest ApproveContact(Guid requestId, bool mutualContacts, bool submitChanges)
        {
            Sc_SharedRequest request = Requests.RequestOperations.GetRequestById(requestId);
            if (request != null)
            {
                Guid requestee = new Guid(request.Context.Element("RequesteeUserId").Value);
                ApproveContact(request.RequestorUserId, requestee, "", mutualContacts, submitChanges);
                
            }
            return request;
        }

        public static void ApproveContact(Guid requestor, Guid requestee, string comment, bool mutualContacts, bool submitChanges)
        {
            if(!AreUsersContacts(requestor, requestee))
            {
                Sc_Contact t = new Sc_Contact();
                t.SeqId = Guid.NewGuid();
                t.UserIdA = requestor;
                t.USerIdB = requestee;
                t.Comment = comment;
                t.StatusChangeDate = DateTime.Now;
                scDataContext.Instance.Sc_Contacts.InsertOnSubmit(t);

                XElement context = new XElement("Context",
                     new XAttribute("XsltFolderInMod", "Contact"),
                     new XElement("Event",
                         new XAttribute("Name", "ContactApproved"),
                         new XElement("RequesteeUserId", requestee)));
                MessageOperations.SendSystemMessage(requestee, requestor, "ContactApproved", context, true);

                if (mutualContacts)
                {
                    Sc_Contact t1 = new Sc_Contact();
                    t1.SeqId = Guid.NewGuid();
                    t1.UserIdA = requestee;
                    t1.USerIdB = requestor;
                    t1.Comment = string.Empty;
                    t1.StatusChangeDate = DateTime.Now;
                    scDataContext.Instance.Sc_Contacts.InsertOnSubmit(t1);
                }
            }

            if (submitChanges)
            {
                scDataContext.Instance.SubmitChanges();
            }
        }

        ////public static bool ChangePendingRequestStatus(enums.ContactRequestStatus status, Guid requestId, string comment)
        ////{
        ////    bool ret = true;
        ////    DateTime changeDate = DateTime.Now;
        ////    try
        ////    {
        ////        Sc_Contact r = scDataContext.Instance.Sc_Contacts.Single(d => d.SeqId == requestId);
        ////        if (r.Status == SharingCenter.Web.Classes.enums.ContactRequestStatus.Pending)
        ////        {
        ////            r.Status = status;
        ////            r.StatusChangeDate = changeDate;
        ////            r.Comment = comment;
        ////        }

        ////        if (status == SharingCenter.Web.Classes.enums.ContactRequestStatus.Approved)
        ////        {
        ////            Sc_Contact m;
        ////            try
        ////            {
        ////                m = scDataContext.Instance.Sc_Contacts.Single(d => (d.UserIdA == r.USerIdB && d.USerIdB == r.UserIdA));

        ////            }
        ////            catch
        ////            {
        ////                m = new Sc_Contact();
        ////                m.SeqId = Guid.NewGuid();
        ////                m.UserIdA = r.USerIdB;
        ////                m.USerIdB = r.UserIdA;
        ////                m.Comment = "系统自动确认";
        ////                scDataContext.Instance.Sc_Contacts.InsertOnSubmit(m);
        ////            }
        ////        }

        ////        scDataContext.Instance.SubmitChanges();
        ////    }
        ////    catch { ret = false; }

        ////    return ret;
        ////}
        public static List<Sc_SharedRequest> GetPendingRequestors(Guid requestee)
        {
            return Requests.RequestOperations.GetRequestsByEntityType(EntityType.Contact, requestee, RequestStatus.Pending, LogicalOperator.Is);
        }

        public static Guid? AddContactRequest(Guid requestor, Guid requestee, string comment)
        {
            if (!AreUsersContacts(requestor, requestee))
            {
                XElement context = new XElement("ContactRequestContext",
                    new XElement("RequestorUserId", WebProfile.Current.UserId),
                    new XElement("RequesteeUserId", requestee),
                    new XElement("Comment", comment)
                    );
                return Requests.RequestOperations.AddRequest(EntityType.Contact,requestee, requestor, requestee, context).RequestId;
            }
            return null;
        }

        /// <summary>
        /// Get a list of contacts user id based on a user id
        /// </summary>
        /// <param name="userId">The user id to request</param>
        /// <returns>List of user id</returns>
        public static List<Guid> GetContacts(Guid userId)
        {
            //List<Guid> contactList = new List<Guid>();
            var q = from c in scDataContext.Instance.Sc_Contacts
                    where c.UserIdA == userId
                    select c.USerIdB;

            return q.ToList();
        }

        public static List<Sc_Contact> GetContactsWithDetails(Guid userId)
        {
            var q = from c in scDataContext.Instance.Sc_Contacts
                    where c.UserIdA == userId
                    select c;
            return q.ToList();
        }

        public static void DeleteContact(Guid userIdA, Guid userIdB)
        {
            scDataContext.Instance.DeleteContact(userIdA, userIdB);
        }

    }
}
